﻿using System;
using Microsoft.Crm.Sdk;

namespace Crm.Plugins.DuplicateChecker{
    /// <summary>
    /// 
    /// </summary>
    public class DuplicateCheckerPlugin : IPlugin{
        // This should match your Crm Schema Prefix. Default is new_
        // TODO: Query this from ICrmService.
        private const string SCHEMAPREFIX = "new_";

        /// <summary>
        /// Executes the duplicate checking and handling on the current context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IPluginExecutionContext context){
            try{
                if (context == null) throw new InvalidPluginExecutionException("PluginExecutionContext cannot be null.");
                lock (this){
                    DynamicEntity targetEntity = (DynamicEntity) context.InputParameters[ParameterName.Target];
                    using (DuplicateHandler duplicateHandler = new DuplicateHandler(context.CreateCrmService(true), targetEntity, SCHEMAPREFIX)){
                        if (duplicateHandler.Find() > 0){
                            throw new InvalidPluginExecutionException(String.Format("Id already exists. Entity:{0}  Id:{1}", targetEntity.Name,
                                                                                    duplicateHandler.EntityId));
                        }
                    }
                }
            }
            catch (Exception exception){
              EventLogger.WriteApplicationEvent(exception.ToString(), GetType());
                throw;
            }
        }
    }
}